import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import { Form, Input, Select } from 'antd'
const FormConfig = forwardRef((props: { roleList: any }, ref) => {
    const { roleList } = props
    const [form] = Form.useForm()
    const [roleOptions, setRoleOptions] = useState<any[]>([])

    useEffect(() => {
        // 把传入的 roleList 映射为 Antd Select 可识别的 options，统一 value 为字符串以便回显匹配
        const opts = (roleList || []).map((r: any) => ({
            label: r.label ?? r.name ?? r.roleName ?? String(r.title ?? ''),
            value: String(typeof r.value !== 'undefined' ? r.value : r.id ?? '')
        }))
        setRoleOptions(opts)
    }, [roleList])

    useImperativeHandle(ref, () => ({
        // 包装 setFieldsValue：如果传入包含 role，则把 role 转为字符串以匹配 options.value
        setFieldsValue: (vals: any) => {
            if (vals && vals.role !== undefined && vals.role !== null) {
                vals = { ...vals, role: String(vals.role) }
            }
            return form.setFieldsValue(vals)
        },
        submit: () => form.validateFields(),
        reset: () => form.resetFields(),
    }))
    return (
        <Form
            form={form}
            name="basic"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            initialValues={{ remember: true }}
            autoComplete="off"
            layout="horizontal"
        >
            <Form.Item
                label="用户名"
                name="name"
                rules={[{ required: true, message: '请输入用户名' }]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="年龄"
                name="age"
                rules={[{ required: true, message: '请输入年龄' }]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="地址"
                name="address"
                rules={[{ required: true, message: '请输入地址' }]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="角色"
                name="role"
                rules={[{ required: true, message: '请选择角色' }]}
            >
                <Select
                    style={{ width: 120 }}
                    options={roleOptions}
                    placeholder="请选择角色"
                />
            </Form.Item>
            <Form.Item label="id" name="id" hidden={true}>
                <Input />
            </Form.Item>
        </Form>
    )
})

export default FormConfig
